package com.cci.kangdao.service.impl;

import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.ServiceManagerAffirmService;
import com.cci.kangdao.task.AsyncTask;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service("ServiceManagerAffirmService")
public class ServiceManagerAffirmServiceImpl implements ServiceManagerAffirmService {

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Autowired
	private ServiceManagerAffirmDao serviceManagerAffirmDao;

	@Resource
	private WorkOrderRepairDao workOrderRepairDao;

	@Resource
	private AsyncTask asyncTask;

	@Resource
	private LoginDao loginDao;

	@Resource
	private CRMPlatformServiceDao platformServiceDao;
	
	@Autowired
	private ConfirmationByServiceManagerDao confirmationByServiceManagerDao;

	@Autowired
	private RedisClientUtils redisClientUtils;

	//区域服务经理审核通过
	@Override
	@Transactional
	public ModelAndView affirm(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		try {
			Map<String, Object> newmap = new HashMap<String, Object>();
			// 根据App传入字段userId查询user_T表ID
			String userid = MapUtils.getString(map, "UserId");
			System.out.println(userid);
			UserT userByid = loginDao.getUserByid(userid);
			long id = userByid.getId();
			String contact = userByid.getContact();
			String phone = userByid.getPhone();
			map.put("contact", contact);
			map.put("phone", phone);
			map.put("updator", id);
			map.put("UpdateTime", (String)map.get("updateTime"));  //前端传来的这条工单的修改时间
			// 获取实际当前时间(服务器时间加8小时)
			String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
			map.put("updateTime", realCurrentTime);
			map.put("ProcessComment","");
			// 工单来源
			int OrderSource = MapUtils.getIntValue(map, "OrderSource");

			/**
			 * 根据工单来源判断服务经理确认后的工单状态是什么 OrderSource 0 终端用户APP报修 OrderSource 1
			 * 服务站APP报修 OrderSource 2 用户400报修 OrderSource 3 服务站CRM报修 a)
			 * 工单来源=用户在线报修 /用户联系CSC热线，工单确认后，工单状态显示：待服务商接单 OrderStatus 4 b)
			 * 工单来源=服务站APP创建工单/服务站CRM创建工单，oldRelOrderId不为null
			 * 工单确认后，工单状态显示：待服务商接单 OrderStatus 4 oldRelOrderId为null
			 * 工单确认后，工单状态显示：待派服务技师 OrderStatus 6
			 */
			// 关联工单表查看是否改派
			Map<String, Object> oldRelOrderId = serviceManagerAffirmDao.getRelOrderIdOld(map);
			String relOrderIdOld = MapUtils.getString(oldRelOrderId, "RelOrderIdOld");
			System.out.println(relOrderIdOld);
			// 工单编号
			String OrderNo = MapUtils.getString(map, "OrderNo");
			JSONObject obj = new JSONObject();

			JSONArray jsonArr = new JSONArray();
			JSONObject content;
            if (OrderSource == 0 || OrderSource == 2 || OrderSource == 4 || OrderSource == 6) {
                /**
                 * 更新服务工单为待服务商接单
                 */
				// 修改工单表工单状态，用户在线报修 /用户联系CSC热线/CSC工单改派
                map.put("isShowStation", 0);
				int updateUser = serviceManagerAffirmDao.updateUser(map);
				if (updateUser > 0) {

					// 根据页面传过来的工单Id查询工单最新状态
					Map<String, Object> workOrderMap = new HashMap<String, Object>();
					workOrderMap = workOrderRepairDao.getCurrentWorkOrder(map);
					String serviceSubtype = MapUtils.getString(workOrderMap, "ServiceSubtype", "");
					String sellType = MapUtils.getString(workOrderMap, "SellType", "");
					// 服务站渠道
					int OrderChannel = MapUtils.getIntValue(workOrderMap, "OrderChannel");
					map.put("OrderChannel", OrderChannel);
					// 根据服务站ID和服务站渠道查询工单状态同步crm所需要的BusinessNo（stationNo）
					Map<String, Object> ssRepair = confirmationByServiceManagerDao.getSSRepair(map);
					String BusinessNo = MapUtils.getString(ssRepair, "BusinessNo");
					map.put("BusinessNo", BusinessNo);
					
					// 将旧工单状态同步至CRM
					Map<String, Object> tbMap = new HashMap<String, Object>();
					tbMap = OrderStatusToCrmMap(workOrderMap, map);
					tbMap.put("phoneIMEI",MapUtils.getString(map,"IMEI",""));
					tbMap.put("positionLat",MapUtils.getFloatValue(map,"PositionLat",0));
					tbMap.put("positionLon",MapUtils.getFloatValue(map,"PositionLon",0));
					tbMap.put("location",MapUtils.getString(map,"Location",""));
					if(OrderChannel == 4){
						tbMap.put("isAutoPass",0);  //是否自动审批通过   0：否   1：是
					}
					try {
						CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
								.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(),platformServiceDao,redisClientUtils,tbMap,null);
						if(CRMres.getStatus() != 0) {
							log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}
					
					// 根据服务站id查询站长、服务商信息员
					List<Map<String, Object>> messengerAndStationmaster = serviceManagerAffirmDao
							.getMessengerAndStationmaster(map);
					if (messengerAndStationmaster != null) {
						map.put("OrderStatus", 4);
						map.put("ProcessStatus", 4);
						for (Map<String, Object> map2 : messengerAndStationmaster) {
							long UserId = (long) map2.get("UserID");
							newmap.put("OrderId", map.get("OrderId"));
							newmap.put("OrderStatus", 4);
							newmap.put("UserId", UserId);
							newmap.put("updator", id);
							newmap.put("updateTime", realCurrentTime);
							// 插入工单负责人表
							int insertWorkOrderPrincipal = serviceManagerAffirmDao.insertWorkOrderPrincipal(newmap);
							System.out.println(insertWorkOrderPrincipal);
						}
						String Content = "您有新工单信息，工单号" + OrderNo + "，";
						if(OrderChannel == 1){
							Content = Content + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
						}
						Content = Content + "请尽快处理！";
						map.put("Content", Content);
						// 插入工单操作记录表
						int insertWorkOrderFlow = serviceManagerAffirmDao.insertWorkOrderFlow(map);
						System.out.println(insertWorkOrderFlow);

						// //插入消息提醒记录表
						map.put("roleNames", "'站长','服务商信息员'");
						map.put("roleNo", "'R0041','R0069'");
						List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
						sendList = workOrderRepairDao.getSendList(map, Arrays.asList("R0041","R0069"));
						if (null != sendList && sendList.size() > 0) {
							// 准备发送信息
							Map<String, Object> otherMap = new HashMap<String, Object>();
							String smsgbody = Content;
							String stransmsg = Content;
							otherMap.put("msgBody", smsgbody);
							otherMap.put("msgTransMsg", stransmsg);
							otherMap.put("msgTitle", "新工单提醒");
							otherMap.put("function", 2);
							otherMap.put("category", 1);
							otherMap.put("Creator", id);
							otherMap.put("CreateTime", realCurrentTime);
							workOrderMap.put("ProcessorId",id);
							// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
							List<Map<String, Object>> sendMsgResultList = asyncTask
									.sendMsg(workOrderMap, sendList, 1, 1, otherMap);
							// 将信息发送结果记录到数据库
							if(CollectionUtils.isNotEmpty(sendMsgResultList)){
								int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
							}
						}
						try {
							obj.put("status", 0);
							obj.put("msg", "");
							obj.put("data", "");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}else {  //工单状态没有修改成功
					obj.put("status", SMSEnum.type21.getIndex());
					obj.put("msg", SMSEnum.type21.getName());
					obj.put("data", "");
					// 主动回滚事务
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}

			} else {
				if (StringUtils.isBlank(relOrderIdOld)) {

					/**
					 * 更新服务工单为待派服务技师
					 */
					// 修改工单表工单状态，服务站APP创建工单/服务站CRM创建工单
                    map.put("isShowStation", 0);
					int updateServiceStation = serviceManagerAffirmDao.updateServiceStation(map);
					if (updateServiceStation > 0) {

						// 根据页面传过来的工单Id查询工单最新状态
						Map<String, Object> workOrderMap = new HashMap<String, Object>();
						workOrderMap = workOrderRepairDao.getCurrentWorkOrder(map);

						// 服务站渠道
						int OrderChannel = MapUtils.getIntValue(workOrderMap, "OrderChannel");
						map.put("OrderChannel", OrderChannel);
						// 根据服务站ID和服务站渠道查询工单状态同步crm所需要的BusinessNo（stationNo）
						Map<String, Object> ssRepair = confirmationByServiceManagerDao.getSSRepair(map);
						String BusinessNo = MapUtils.getString(ssRepair, "BusinessNo");
						map.put("BusinessNo", BusinessNo);
						
						// 将旧工单状态同步至CRM
						Map<String, Object> tbMap = new HashMap<String, Object>();
						tbMap = OrderStatusToCrmMap(workOrderMap, map);
						tbMap.put("phoneIMEI",MapUtils.getString(map,"IMEI",""));
						tbMap.put("positionLat",MapUtils.getFloatValue(map,"PositionLat",0));
						tbMap.put("positionLon",MapUtils.getFloatValue(map,"PositionLon",0));
						tbMap.put("location",MapUtils.getString(map,"Location",""));
						if(OrderChannel == 4){
							tbMap.put("isAutoPass",0);  //是否自动审批通过   0：否   1：是
						}
						try {
							CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
									.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
							if(CRMres.getStatus() != 0) {
								log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
							}
						} catch (Exception e) {
							e.printStackTrace();
							log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
						}
						
						// 根据服务站id查询站长、服务商信息员
						List<Map<String, Object>> messengerAndStationmaster = serviceManagerAffirmDao
								.getMessengerAndStationmaster(map);
						if (messengerAndStationmaster != null) {
							map.put("OrderStatus", 6);
							map.put("ProcessStatus", 6);
							for (Map<String, Object> map2 : messengerAndStationmaster) {
								long UserId = (long) map2.get("UserID");
								newmap.put("OrderId", map.get("OrderId"));
								newmap.put("OrderStatus", 6);
								newmap.put("UserId", UserId);
								newmap.put("updator", id);
								newmap.put("updateTime", realCurrentTime);
								// 插入工单负责人表
								int insertWorkOrderPrincipal = serviceManagerAffirmDao.insertWorkOrderPrincipal(newmap);
								System.out.println(insertWorkOrderPrincipal);
							}
							String Content = "您有工单待指派技师，工单号" + OrderNo + "，请尽快处理！";
							map.put("Content", Content);
							// 插入工单操作记录表
							int insertWorkOrderFlow = serviceManagerAffirmDao.insertWorkOrderFlow(map);
							System.out.println(insertWorkOrderFlow);

							// 插入消息提醒记录表
							map.put("roleNames", "'站长','服务商信息员'");
							map.put("roleNo", "'R0041','R0069'");
							List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
							sendList = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
							if (null != sendList && sendList.size() > 0) {
								// 准备发送信息
								Map<String, Object> otherMap = new HashMap<String, Object>();
								String smsgbody = Content;
								String stransmsg = Content;
								otherMap.put("msgBody", smsgbody);
								otherMap.put("msgTransMsg", stransmsg);
								otherMap.put("msgTitle", "新工单提醒");
								otherMap.put("function", 2);
								otherMap.put("category", 1);
								otherMap.put("Creator", id);
								otherMap.put("CreateTime", realCurrentTime);
								workOrderMap.put("ProcessorId",id);
								// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
								List<Map<String, Object>> sendMsgResultList = asyncTask
										.sendMsg(workOrderMap, sendList, 1, 1, otherMap);
								// 将信息发送结果记录到数据库
								if(CollectionUtils.isNotEmpty(sendMsgResultList)){
									int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
								}
							}
							try {
								obj.put("status", 0);
								obj.put("msg", "");
								obj.put("data", "");
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}else {
						//工单状态没有修改成功
						obj.put("status", SMSEnum.type21.getIndex());
						obj.put("msg", SMSEnum.type21.getName());
						obj.put("data", "");
						// 主动回滚事务
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						//返回客户
						ParameterTool.writeResponse(response, obj.toString());
						return null;
					}
				} else {

					// 修改工单表工单状态，服务站APP创建工单/服务站CRM创建工单
                    map.put("isShowStation", 0);
					int updateServiceStation = serviceManagerAffirmDao.updateServiceStation(map);
					if (updateServiceStation > 0) {

						// 根据页面传过来的工单Id查询工单最新状态
						Map<String, Object> workOrderMap = new HashMap<String, Object>();
						workOrderMap = workOrderRepairDao.getCurrentWorkOrder(map);
						String serviceSubtype = MapUtils.getString(workOrderMap, "ServiceSubtype", "");
						String sellType = MapUtils.getString(workOrderMap, "SellType", "");
						// 服务站渠道
						int OrderChannel = MapUtils.getIntValue(workOrderMap, "OrderChannel");
						map.put("OrderChannel", OrderChannel);
						// 根据服务站ID和服务站渠道查询工单状态同步crm所需要的BusinessNo（stationNo）
						Map<String, Object> ssRepair = confirmationByServiceManagerDao.getSSRepair(map);
						String BusinessNo = MapUtils.getString(ssRepair, "BusinessNo");
						map.put("BusinessNo", BusinessNo);
						
						// 将旧工单状态同步至CRM
						Map<String, Object> tbMap = new HashMap<String, Object>();
						tbMap = OrderStatusToCrmMap(workOrderMap, map);
						tbMap.put("phoneIMEI",MapUtils.getString(map,"IMEI",""));
						tbMap.put("positionLat",MapUtils.getFloatValue(map,"PositionLat",0));
						tbMap.put("positionLon",MapUtils.getFloatValue(map,"PositionLon",0));
						tbMap.put("location",MapUtils.getString(map,"Location",""));
						if(OrderChannel == 4){
							tbMap.put("isAutoPass",0);  //是否自动审批通过   0：否   1：是
						}
						try {
							CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
									.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
							if(CRMres.getStatus() != 0) {
								log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
							}
						} catch (Exception e) {
							e.printStackTrace();
							log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
						}
						
						// 根据服务站id查询站长、服务商信息员
						List<Map<String, Object>> messengerAndStationmaster = serviceManagerAffirmDao
								.getMessengerAndStationmaster(map);
						if (messengerAndStationmaster != null) {
							map.put("OrderStatus", 6);
							map.put("ProcessStatus", 6);
							for (Map<String, Object> map2 : messengerAndStationmaster) {
								long UserId = (long) map2.get("UserID");
								newmap.put("OrderId", map.get("OrderId"));
								newmap.put("OrderStatus", 6);
								newmap.put("UserId", UserId);
								newmap.put("updator", id);
								newmap.put("updateTime", realCurrentTime);
								// 插入工单负责人表
								int insertWorkOrderPrincipal = serviceManagerAffirmDao.insertWorkOrderPrincipal(newmap);
								System.out.println(insertWorkOrderPrincipal);
							}

							String Content = "您有新工单信息，工单号" + OrderNo + "，";
							if(OrderChannel == 1){
								Content = Content + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
							}
							Content = Content + "请尽快处理！";
							map.put("Content", Content);
							// 插入工单操作记录表
							int insertWorkOrderFlow = serviceManagerAffirmDao.insertWorkOrderFlow(map);
							System.out.println(insertWorkOrderFlow);

							// 插入消息提醒记录表
							map.put("roleNames", "'站长','服务商信息员'");
							map.put("roleNo", "'R0041','R0069'");
							List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
							sendList = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
							if (null != sendList && sendList.size() > 0) {
								// 准备发送信息
								Map<String, Object> otherMap = new HashMap<String, Object>();
								String smsgbody = Content;
								String stransmsg = Content;
								otherMap.put("msgBody", smsgbody);
								otherMap.put("msgTransMsg", stransmsg);
								otherMap.put("msgTitle", "新工单提醒");
								otherMap.put("function", 2);
								otherMap.put("category", 1);
								otherMap.put("Creator", id);
								otherMap.put("CreateTime", realCurrentTime);
								workOrderMap.put("ProcessorId",id);
								// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
								List<Map<String, Object>> sendMsgResultList = asyncTask
										.sendMsg(workOrderMap, sendList, 1, 1, otherMap);
								// 将信息发送结果记录到数据库
								if(CollectionUtils.isNotEmpty(sendMsgResultList)){
									int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
								}
							}
							try {
								obj.put("status", 0);
								obj.put("msg", "");
								obj.put("data", "");
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}else {
						//工单状态没有修改成功
						obj.put("status", SMSEnum.type21.getIndex());
						obj.put("msg", SMSEnum.type21.getName());
						obj.put("data", "");
						// 主动回滚事务
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						//返回客户
						ParameterTool.writeResponse(response, obj.toString());
						return null;
					}
				}

			}
			ParameterTool.writeResponse(response, obj.toString());
		} catch (Exception ex) {
			// TODO: handle exception
			log.error(ex.getMessage(), ex);
			ParameterTool.writeErrorResponse(response);
			// 主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return null;
	}
	
	public Map<String, Object> OrderStatusToCrmMap(Map<String, Object> orgOrderMap, Map<String, Object> map) {
		Map<String, Object> tbMap = new HashMap<String, Object>();
		tbMap.put("orderNo", orgOrderMap.get("OrderNo"));
		if (!"".equals(MapUtils.getString(orgOrderMap, "OrderNoCrm", ""))) {
			tbMap.put("CRMNo", orgOrderMap.get("OrderNoCrm"));
		}
		tbMap.put("oldOrderNo", map.get("oldOrderNo"));
		tbMap.put("billStatus", orgOrderMap.get("OrderStatus"));
		if (map.containsKey("RefuseType")){
			tbMap.put("refuseType", map.get("RefuseType"));// 2 用户不需要维修
		}
		tbMap.put("refuseReason", map.get("RefuseContent"));
		tbMap.put("actionTime", LocalTimeUtil.getRealCurrentTime());
		tbMap.put("directorName", map.get("contact"));
		tbMap.put("directorPhone", map.get("phone"));
		tbMap.put("stationNo", map.get("BusinessNo"));

		return tbMap;
	}


}
